package com.tianyi.controller;

import com.tianyi.controller.menu.MenuController;
import com.tianyi.dao.entity.roleMenuRecord.RoleMenuRecord;
import com.tianyi.dao.mapper.RoleMenuRecordMapper;
import com.tianyi.env.EnvService;
import com.tianyi.lib.enums.SysUserTypes;
import com.tianyi.lib.req.BaseReq;
import com.tianyi.model.SimpleLoginUser;
import com.tianyi.role.RoleBaseService;
import com.tianyi.role.RoleService;
import com.tianyi.util.SimpleUserUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * base controller
 *
 * @author cuixuhui
 * @date 2019/11/26
 */
public class BaseController {

    private static final Logger logger = LoggerFactory.getLogger(BaseController.class);

    @Autowired
    private RoleService roleService;

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }

    @Autowired
    protected HttpServletRequest request;
    @Autowired
    protected EnvService envService;

    protected SimpleLoginUser getUserFromRequest(){

//        if (envService.isDaily()){
//            SimpleLoginUser user = new SimpleLoginUser();
//            user.setEmpId(1L);
//            user.setUserName("admin");
//            user.setUserType(SysUserTypes.ADMIN);
//            return user;
//        }
        try {
            SimpleLoginUser loginUser = SimpleUserUtils.getUserFromReq(request);
            if(loginUser != null) {
                Long roleId = loginUser.getRoleId();
                if(roleId != null) {
                    List<Long> menuIds = roleService.getMenuIdsByRoleId(roleId);
                    loginUser.setMenuIds(menuIds);
                }
            }
            return loginUser;
        }catch (Exception e){
            logger.info("getUserFromRequest error {}", e.getMessage());
        }
        return null;
    }

    protected void handLoginUser(BaseReq req){

        SimpleLoginUser loginUser = getUserFromRequest();
        if (Objects.isNull(loginUser)){
            return;
        }
        req.setEmpId(loginUser.getEmpId());
        req.setLoginName(loginUser.getUserName());
    }
}
